<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Admin_Model_User extends Zend_Db_Table{
	
	protected $_name    = "users";
    protected $_primary = "id";
    
    public function saveData($data = array()){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            if(isset($data['id']) && $this->checkExists($data['id'])){
                $id = $data['id'];
                $db->update("users", $data, "id = $id");
            }else{
                $db->insert('users', $data);
            }
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('user'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function getData($id = null){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        $cols = array('id', 'name', 'address', 'phone_number', 'email', 'username', 'group', 'block', 'status', 'role', 'register_date');
        
        $select = $db->select()
                    ->from(array('u' => 'users'), $cols);
        
        if($id != null){
            $select->where("u.id = ?", $id, 'INTEGER');
            
            $db->setFetchMode(Zend_Db::FETCH_ASSOC);
            $result = $db->fetchRow($select);
        }else{
            $select->order('u.id DESC');
            
            $result = $db->fetchAll($select);
        }
        
        return $result;
    }
    
    public function getAllData(){
    	return $this->getData();
    }
    
    public function deleteData($id){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $db->delete('users', "id = $id");
            
            $cache = new Zenddn_System_Cache();
            $cache->clean(array('user'));
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($id){
        $option = array('table' => 'users', 'field' => 'id');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($id)){
            return true;
        }
        
        return false;
    }
}